﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.BL.UserManagement;
using BEGDC.CC.BL.Common;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;
using NetBpm.Util.Client;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;
using ASBCC.Business;

namespace BEGDC.CC.Web
{
	/// <summary>
	/// Summary description for main.
	/// </summary>
	public class OperationLog : System.Web.UI.Page
	{
		/// <summary>
		/// 
		/// </summary>
		private string _Sorting
		{
			get
			{
				if( ViewState["Sorting"] == null ) return string.Empty;

				return ViewState["Sorting"].ToString(); 
			}
			set{ ViewState["Sorting"]=value; }
		}

		protected System.Web.UI.WebControls.TextBox txtStartDate;
		protected System.Web.UI.WebControls.TextBox txtEndDate;
		protected System.Web.UI.WebControls.Button btnSearch;
		protected System.Web.UI.WebControls.DataGrid dgTaskList;
		protected System.Web.UI.WebControls.Label lblRecordCount;
		protected System.Web.UI.WebControls.Label lblCurrentPageIndex;
		protected System.Web.UI.WebControls.Label lblPageCount;
		protected System.Web.UI.WebControls.ImageButton btnPageFirst;
		protected System.Web.UI.WebControls.ImageButton btnPagePrev;
		protected System.Web.UI.WebControls.ImageButton btnPageNext;
		protected System.Web.UI.WebControls.ImageButton btnPageLast;
		protected System.Web.UI.WebControls.TextBox txtPage;
		protected System.Web.UI.WebControls.ImageButton btnGotoPage;
		protected System.Web.UI.HtmlControls.HtmlImage StartDateImg;
		protected System.Web.UI.WebControls.Label lblDescription;
		protected System.Web.UI.WebControls.Button btnExport;
		protected System.Web.UI.HtmlControls.HtmlImage EndlDateImg;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				// Put user code to initialize the page here
				if(!Page.IsPostBack)
				{
					this.txtPage.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('"+this.btnGotoPage.UniqueID+"').click();return false;}} else {return true}; ");
					string type = Page.Request.QueryString["type"];
					
					if ( type == null)
					{
						this.IsWorkflowOperationLog  = false;
						//						this.lblDescription.Text = "Operation Log";
					}
					else 
					{
						this.IsWorkflowOperationLog = true;
						//						this.lblDescription.Text = "Workflow Operation Log";
					}
		
					this.BindData(1);
				}
				else
				{
					if (Page.Request.Form[0].IndexOf("dgTaskList") > -1)
					{
						this.BindData(this._CurrentPageIndex);
					}
				}

			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch(Exception ex)
			{
				string s = ex.Message;
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private bool IsWorkflowOperationLog
		{
			get
			{
				if( ViewState["IsWorkflowOperationLog"] != null ) return (bool) ViewState["IsWorkflowOperationLog"];
				else
					return false;
			}
			set
			{
				ViewState["IsWorkflowOperationLog"] = value;
			}
		}

		private void BindData(int pageIndex)
		{
			this.CreateGridColumn();
            //this.txtStartDate.Text = PageSafeHelper.SafeText(this.txtStartDate.Text);
            //this.txtEndDate.Text = PageSafeHelper.SafeText(this.txtEndDate.Text);
			if (this.txtStartDate.Text == string.Empty || this.txtEndDate.Text == string.Empty)
			{
				this.txtStartDate.Text = System.DateTime.Today.AddDays(-1).ToString("M/d/yyyy");
				this.txtEndDate.Text = System.DateTime.Today.AddDays(1).ToString("M/d/yyyy");
			}

			string start = this.txtStartDate.Text;
			string end = this.txtEndDate.Text;

			IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
			System.Data.DataTable dtLogs = utility.GetOperationLog(start, end, this.IsWorkflowOperationLog);

			int count = dtLogs.Rows.Count;
			
			if (!this.dgTaskList.AllowPaging && count > 65500)
			{
				_RowCount = count;
				return;
			}
				
			if (this._Sorting != string.Empty)
			{
				dtLogs.DefaultView.Sort = this._Sorting;
			}

			this.dgTaskList.DataSource = dtLogs.DefaultView;
			this.dgTaskList.DataBind();

			SetPageCount(count, pageIndex);
			

		}
        //public string GetCurrentLog(bool IsWorkflowLog)
        //{
        //    string type = Page.Request.QueryString["type"];
        //    if ( type == null)
        //    {
        //        if (!IsWorkflowLog)
        //            return "TAB_1";
				
        //    }
        //    else 
        //    {
        //        if (IsWorkflowLog)
        //            return "TAB_1";
        //    }
        //    return "TAB_2";
			
        //}

        protected string GetTabClass(bool flag)
        {
            string t = Request.QueryString["type"];
            if (String.IsNullOrEmpty(t))
                return flag ? "tab_active" : "tab_link";
            else
                return !flag ? "tab_active" : "tab_link";
        }

		public void CreateGridColumn()
		{
			if (this.dgTaskList.Columns.Count > 0)
				return;
			System.Web.UI.WebControls.BoundColumn newCol = new  BoundColumn();
			newCol.HeaderText = "Time<br/>时间";
			newCol.DataField = "Time";
			newCol.ReadOnly = true;
			newCol.ItemStyle.Width = 150;
			newCol.Visible = true ;
			newCol.SortExpression= newCol.DataField;
			this.dgTaskList.Columns.Add(newCol) ;

			newCol = new  BoundColumn();
            newCol.HeaderText = "Operator<br/>操作人";
			newCol.DataField = "OperatorName";
			newCol.ReadOnly = true;
			newCol.ItemStyle.Width = 120;
			newCol.Visible = true ;
			newCol.SortExpression= newCol.DataField;
			this.dgTaskList.Columns.Add(newCol) ;

			newCol = new  BoundColumn();
            newCol.HeaderText = "Department<br/>部门";
			newCol.DataField = "Department";
			newCol.ReadOnly = true;
			newCol.ItemStyle.Width = 150;
			newCol.Visible = true ;
			newCol.SortExpression= newCol.DataField;
			this.dgTaskList.Columns.Add(newCol) ;

			if (!this.IsWorkflowOperationLog)
			{
				newCol = new  BoundColumn();
                newCol.HeaderText = "Module<br/>时间";
				newCol.DataField = "Module";
				newCol.ReadOnly = true;
				newCol.ItemStyle.Width = 150;
				newCol.Visible = true ;
				newCol.SortExpression= newCol.DataField;
				this.dgTaskList.Columns.Add(newCol) ;

			}
			else
			{
				newCol = new  BoundColumn();
                newCol.HeaderText = "Application#<br/>单号";
				newCol.DataField = "AppNO";
				newCol.ReadOnly = true;
				newCol.ItemStyle.Width = 100;
				newCol.Visible = true ;
				newCol.SortExpression= newCol.DataField;
				this.dgTaskList.Columns.Add(newCol) ;

				newCol = new  BoundColumn();
                newCol.HeaderText = "Current Step<br/>当前步骤";
				newCol.DataField = "CurrentStep";
				newCol.ReadOnly = true;
				newCol.ItemStyle.Width = 100;
				newCol.Visible = true ;
				newCol.SortExpression= newCol.DataField;
				this.dgTaskList.Columns.Add(newCol) ;

				newCol = new  BoundColumn();
                newCol.HeaderText = "Operation Type<br/>操作类型";
				newCol.DataField = "OperationType";
				newCol.ReadOnly = true;
				newCol.ItemStyle.Width = 100;
				newCol.Visible = true ;
				newCol.SortExpression= newCol.DataField;
				this.dgTaskList.Columns.Add(newCol) ;

			}
			newCol = new  BoundColumn();
            newCol.HeaderText = "Description<br/>描述";
			newCol.DataField = "Description";
			newCol.ReadOnly = true;
			newCol.ItemStyle.Width = 150;
			newCol.Visible = true ;
			this.dgTaskList.Columns.Add(newCol) ;

		}




		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
			this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
			this.btnPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageFirst_Click);
			this.btnPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.btnPagePrev_Click);
			this.btnPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageNext_Click);
			this.btnPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageLast_Click);
			this.btnGotoPage.Click += new System.Web.UI.ImageClickEventHandler(this.btnGotoPage_Click);
			this.dgTaskList.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgTaskList_SortCommand);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		#region ---------- paging events ----------------
		private void btnPageFirst_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			this.dgTaskList.CurrentPageIndex = 0;
			this.BindData(1);
		}

		private void btnPagePrev_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			if( _CurrentPageIndex == 1 ) return;
			this.dgTaskList.CurrentPageIndex = _CurrentPageIndex-2;
			this.BindData(_CurrentPageIndex - 1);
		}

		private void btnPageNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			if( _CurrentPageIndex == _PageCount ) return;	
			this.dgTaskList.CurrentPageIndex = _CurrentPageIndex;
			this.BindData( _CurrentPageIndex + 1 );
		}

		private void btnPageLast_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			this.dgTaskList.CurrentPageIndex = _PageCount-1;
			this.BindData( _PageCount );
		}

		private void btnGotoPage_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			if (this.txtPage.Text == string.Empty)	
			{
				this.txtPage.Text = "1";
			}
			int gotopage = 1;
			try
			{
				gotopage = Convert.ToInt32(this.txtPage.Text);
			}
			catch{}
			int currentpage = 0;

			if (gotopage >= _PageCount)	
			{
				gotopage = _PageCount;
				currentpage = gotopage - 1;
				if (currentpage < 0) currentpage = 0;
			}
			else if (gotopage <= 0)
			{
				gotopage = 1;
			}
			else
			{
				currentpage = gotopage -1;
			}

			this.dgTaskList.CurrentPageIndex = currentpage;

			this.BindData( gotopage );

			this.txtPage.Text = string.Empty;
		}

		#endregion

		#region page navigation
		private int _PageCount
		{
			get
			{
				if( ViewState["PageCount"] != null ) return (int) ViewState["PageCount"];
				else
					return 0;
			}
			set
			{
				ViewState["PageCount"] = value;
			}
		}
		private int _CurrentPageIndex
		{
			get
			{
				if( ViewState["CurrentPageIndex"] != null ) return (int) ViewState["CurrentPageIndex"];
				else
					return 0;
			}
			set
			{
				ViewState["CurrentPageIndex"] = value;
			}
		}
		private int _RowCount
		{
			get
			{
				if( ViewState["RowCount"] != null ) return (int) ViewState["RowCount"];
				else
					return 0;
			}
			set
			{
				ViewState["RowCount"] = value;
			}
		}
		private void SetPageNavi( int newPage )
		{
			if( newPage <= 1 )
			{
				this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_first_inact.gif";
				this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_pre_inact.gif";
				this.btnPageFirst.Attributes["disabled"] = "true";
				this.btnPagePrev.Attributes["disabled"] = "true";
			}
			else
			{
				this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_first.gif";
				this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_pre.gif";
				this.btnPageFirst.Attributes.Remove("disabled");
				this.btnPagePrev.Attributes.Remove("disabled");
			}

			if( newPage >= _PageCount )
			{
				this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_next_inact.gif";
				this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_last_inact.gif";
				this.btnPageNext.Attributes["disabled"] = "true";
				this.btnPageLast.Attributes["disabled"] = "true";
			}
			else
			{
				this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_next.gif";
				this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_last.gif";
				this.btnPageNext.Attributes.Remove("disabled");
				this.btnPageLast.Attributes.Remove("disabled");
			}

			this.lblCurrentPageIndex.Text = newPage.ToString();
			this.lblPageCount.Text = _PageCount.ToString();
			this.lblRecordCount.Text = _RowCount.ToString();

		}

		private void SetPageCount(int count, int pageIndex)
		{
			if( count > 0 )
			{
				_RowCount = count;
				_PageCount = count / this.dgTaskList.PageSize;
				if( count % this.dgTaskList.PageSize > 0) _PageCount ++;

				_CurrentPageIndex = pageIndex;	
				SetPageNavi( pageIndex );
			}	
			else
			{
				_RowCount = count;
				_PageCount = count;
				_CurrentPageIndex = 0;
				SetPageNavi( 0 );
			}
		}

		#endregion

		private void btnSearch_Click(object sender, System.EventArgs e)
		{
			if (Convert.ToDateTime(this.txtStartDate.Text) > Convert.ToDateTime(txtEndDate.Text))
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.US005 + "');window.location.href=window.location.href;</script>");
				return;
			}

			this.dgTaskList.CurrentPageIndex = 0;
			this.BindData(1);
		}

		private void btnExport_Click(object sender, System.EventArgs e)
		{
			this.dgTaskList.AllowPaging = false;
			this.BindData(1);
			if (this._RowCount > 65500)
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.SM017 + "');window.location.href=window.location.href;</script>");
				return;
			}
			BEGDC.CC.Web.Control.ExportDataGridToExcel.Export(Page, dgTaskList, "OperationLog.xls");
		}

		public void dgTaskList_SortCommand(object source, DataGridSortCommandEventArgs e)
		{
			if (this._Sorting.IndexOf(e.SortExpression) > -1 && this._Sorting == e.SortExpression)
				this._Sorting = e.SortExpression + " desc";
			else
				this._Sorting = e.SortExpression;
			this.BindData(this._CurrentPageIndex);
			
		}
	}
}
